<template>
  <ul class="list">
    <li class="item" v-for="item of letters" :key="item" :ref="item" @click="handleLetterClick" 
    @touchstart="handleTouchStart" @touchmove="handleTouchMove" @touchend="handleTouchEnd" >{{item}}</li>
  </ul>
</template>
<script>
export default {
  name: 'CityAlphabet',
  props: {
    cities: Object
  },
  computed: { // 计算手指的当前的位置 然后返回一个数组
    letters () {
      const letters = []
      for (let i in this.cities) {
        letters.push(i)
      }
      return letters
    }
  },
  data () {
    return {
      touchStatus: false,
      startY: 0,
      timer: null
    }
  },
  updated () {
    this.startY = this.$refs['A'][0].offsetTop
  },
  methods: {
    handleLetterClick (e) {
      // console.log(e.target.innerText)
      this.$emit('change',e.target.innerText)
    },
    handleTouchStart () {
      this.touchStatus = true
    },
    handleTouchMove (e) { 
      if (this.touchStatus) {
       // const startY = this.$refs['A'][0].offsetTop // 手指移动时距离顶部的高度 
       if (this.timer) {
         clearTimeout(this.timer)
       }
       this.timer = setTimeout(() =>{
          const touchY = e.touches[0].clientY - 79     // 高度到达颜色的搜索栏的高度
          const index = Math.floor((touchY - this.startY) / 20) // 手指到达是哪个字母
          if (index >=0 && index < this.letters.length) {
            this.$emit('change',this.letters[index])
          }
       }, 8)
       
      }
    },
    handleTouchEnd () {
      this.touchStatus = false
    }
  }
}
</script>
<style lang="stylus" scoped>
  @import '~styles/varibles.styl'
  .list
   position absolute
   top 1.58rem
   right 0
   bottom 0
   width .4rem
   display flex // 字母居中
   flex-direction column
   justify-content center
   .item
     text-align center
     line-height .4rem
     color $bgColor
</style>
